import threading

from waitress import serve

from apps.settingApi.api.timerTask.task import add_task
from comm.openDbConfig import openDbBase
from manage import app
import multiprocessing
import socket

from msgTkinter import msgTkinterClass
from socketIo.main import start
dbproconfig = openDbBase()

def get_max_threads():
    """
    获取服务器核数用于开启最大线程
    :return:
    """
    try:
        num_cores = multiprocessing.cpu_count()
        max_threads = 2 * num_cores
    except Exception as e:
        return 4
    return max_threads



def is_port_in_use(port):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        try:
            s.bind(('0.0.0.0', port))
            return False
        except OSError:
            return True
def sratMsg():
    msgTkinterClass().a001()
def sratTornado():
    import eventlet as eventlet_
    import eventlet.hubs.epolls
    import eventlet.hubs.kqueue
    import eventlet.hubs.selects
    import dns
    import dns.rdtypes
    import dns.rdtypes.ANY
    import dns.rdtypes.IN
    import dns.rdtypes.CH
    import dns.rdtypes.dnskeybase
    import dns.rdtypes.dsbase
    import dns.rdtypes.euibase
    import dns.rdtypes.mxbase
    import dns.rdtypes.nsbase
    import dns.rdtypes.svcbbase
    import dns.rdtypes.tlsabase
    import dns.rdtypes.txtbase
    import dns.rdtypes.util
    import dns.asyncbackend
    import dns.asyncquery
    import dns.asyncresolver
    import dns.dnssec
    import dns.e164
    import dns.namedict
    import dns.tsigkeyring
    import dns.versioned

    eventlet_.monkey_patch()

    if is_port_in_use(dbproconfig['CHARTPORT'])==True:
        print('禁止重复启动')
        raise  ValueError("禁止重复启动")
    print('启动flask')
    try:
        serve(app, host='0.0.0.0', port=dbproconfig['CHARTPORT'], threads=get_max_threads())
    except Exception as e:
        print('启动失败')
        raise  ValueError("启动失败"+repr(e))
def startSocketio():
    print('启动socketio')
    start()
def starTIme():
    add_task(trigger='interval', seconds=dbproconfig['TIME'])
# 启动线程1进行弹窗提示
thread01 = threading.Thread(target=starTIme, daemon=True, name="1")
thread01.start()
# thread01.join()
# # 启动服务
# sratTornado()
# 启动线程1进行弹窗提示
thread02 = threading.Thread(target=sratTornado, daemon=True, name="2")
thread02.start()
thread02.join()